package org.lhg.activiti.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.lhg.activiti.mapper.UserMapper;
import org.lhg.activiti.model.Group;
import org.lhg.activiti.model.MemberShip;
import org.lhg.activiti.model.User;
import org.lhg.activiti.service.MemberShipService;
import org.lhg.activiti.service.UserService;
import org.lhg.activiti.util.CommonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private MemberShipService memberShipService;
    @Autowired
    private UserMapper userMapper;

    /**
     * 用户登录
     * @param map
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public CommonResult<JSONObject> login(@RequestBody Map<String,String> map)throws Exception{
        Map<String,Object> mapLogin=new HashMap<String,Object>();
        mapLogin.put("username", map.get("username"));
        mapLogin.put("password", map.get("password"));
        mapLogin.put("groupId", map.get("groupId"));
        MemberShip memberShip=memberShipService.login(mapLogin);
        JSONObject result=new JSONObject();
        if(memberShip==null){
            result.put("success", false);
            result.put("errorInfo", "用户名或者密码错误！");
        }else{
            result.put("success", true);
            result.put("username", memberShip.getUser().getId());
            result.put("groupname", memberShip.getGroup().getName());
            result.put("groupId", memberShip.getGroup().getId());
        }
       return CommonResult.success(result);
    }

    /**
     * 获取用户集合
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getUserList",method = RequestMethod.POST)
    public CommonResult<JSONObject> getUserList()throws Exception{
        JSONObject result=new JSONObject();
        List<User> userList=userMapper.getUserList();
        JSONArray rows=JSONArray.parseArray(JSON.toJSONString(userList));
        result.put("rows",rows);
        result.put("success",true);
        return CommonResult.success(result);
    }



}
